import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:timeago/timeago.dart' as timeago;
import '../models/article.dart';
import '../providers/audio_provider.dart';
import '../providers/article_provider.dart' as article_provider;
import '../config/app_theme.dart';
import '../screens/article_detail_screen.dart';

/// 文章卡片组件
class ArticleCard extends StatelessWidget {
  final Article article;

  const ArticleCard({super.key, required this.article});

  @override
  Widget build(BuildContext context) {
    return Consumer<AudioProvider>(
      builder: (context, audioProvider, child) {
        final isCurrentPlaying = audioProvider.currentArticle?.articleId == article.articleId && audioProvider.isPlaying;

        return GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => ArticleDetailScreen(articleId: article.articleId),
              ),
            );
          },
          child: Container(
            margin: const EdgeInsets.only(bottom: 12),
            padding: const EdgeInsets.all(16),
            decoration: const BoxDecoration(), // 透明卡片，无背景无边框
            child: IntrinsicHeight(
              child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 公司 Logo
                _buildCompanyBadge(),
                const SizedBox(width: 12),

                // 文章信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 标题
                      Text(
                        article.title,
                        style: const TextStyle(
                          color: AppTheme.textPrimary,
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                          height: 1.4,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 6),

                      // URL（如果有）
                      if (article.url != null && article.url!.isNotEmpty) ...[
                        Text(
                          article.url!,
                          style: const TextStyle(
                            color: AppTheme.textTertiary,
                            fontSize: 11,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 6),
                      ],

                      // 元数据
                      Row(
                        children: [
                          Flexible(
                            child: Text(
                              article.source ?? '',
                              style: const TextStyle(
                                color: AppTheme.textTertiary,
                                fontSize: 12,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          const Padding(
                            padding: EdgeInsets.symmetric(horizontal: 4),
                            child: Text(
                              '·',
                              style: TextStyle(color: AppTheme.textTertiary),
                            ),
                          ),
                          Text(
                            _formatTime(article.publishTime),
                            style: const TextStyle(
                              color: AppTheme.textTertiary,
                              fontSize: 12,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 12),

                      // 底部信息
                      Row(
                        children: [
                          // 时长
                          Row(
                            children: [
                              const Icon(
                                Icons.play_circle_outline,
                                color: AppTheme.textSecondary,
                                size: 16,
                              ),
                              const SizedBox(width: 4),
                              Text(
                                article.audioDuration ?? '03:45',
                                style: const TextStyle(
                                  color: AppTheme.textSecondary,
                                  fontSize: 12,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                ),

                const SizedBox(width: 12),

                // 播放按钮
                _buildPlayButton(context, isCurrentPlaying),
              ],
            ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildCompanyBadge() {
    return Container(
      width: 64,
      height: 64,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Image.asset(
          'assets/images/titleP.png',
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  Widget _buildPlayButton(BuildContext context, bool isCurrentPlaying) {
    return GestureDetector(
      onTap: () {
        final audioProvider = Provider.of<AudioProvider>(context, listen: false);

        // 检查是否是当前文章
        final isCurrentArticle = audioProvider.currentArticle?.articleId == article.articleId;

        if (isCurrentArticle) {
          // 如果是当前文章，直接切换播放/暂停状态
          if (isCurrentPlaying) {
            audioProvider.pause();
          } else {
            audioProvider.play();
          }
        } else {
          // 如果是不同文章，重新初始化并播放
          audioProvider.initAudio(article.articleId, article, 'cn').then((_) {
            audioProvider.play();
          }).catchError((error) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('播放失败: $error')),
            );
          });
        }
      },
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          gradient: AppTheme.primaryGradient,
          boxShadow: [
            BoxShadow(
              color: AppTheme.primaryColor.withOpacity(0.3),
              blurRadius: 8,
              spreadRadius: 0,
            ),
          ],
        ),
        child: Icon(
          isCurrentPlaying ? Icons.pause : Icons.play_arrow,
          color: Colors.white,
          size: 20,
        ),
      ),
    );
  }

  String _formatTime(String? time) {
    if (time == null) return '';
    try {
      final dateTime = DateTime.parse(time);
      timeago.setLocaleMessages('zh_CN', timeago.ZhCnMessages());
      return timeago.format(dateTime, locale: 'zh_CN');
    } catch (e) {
      return time;
    }
  }
}

